//
//  FoodSearchTableViewController.m
//  B
//
//  Created by lanou on 16/5/10.
//  Copyright © 2016年 裴启航. All rights reserved.
//

#import "FoodSearchTableViewController.h"
#import "FoodSearch.h"
#import "FoodSearchTableViewCell.h"
#import "FoodDetailViewController.h"

@interface FoodSearchTableViewController ()
@property (nonatomic, strong) NSMutableArray *listArrs;
@property (nonatomic, strong) NSDictionary *listDic;
@property (nonatomic, assign) NSInteger count;
@end

@implementation FoodSearchTableViewController

- (NSDictionary *)listDic
{
    if (!_listDic) {
        _listDic = [NSDictionary dictionary];
    }
    return _listDic;
}

- (NSMutableArray *)listArrs
{
    if (!_listArrs) {
        _listArrs = [NSMutableArray array];
    }
    return _listArrs;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    self.count = 2;
    self.tableView.bounces = NO;
    [self.tableView registerNib:[UINib nibWithNibName:@"FoodSearchTableViewCell" bundle:nil] forCellReuseIdentifier:@"cell"];
    [self requestFoodData];
    // 上拉加载
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRereshing)];
}

- (void)footerRereshing
{
    NSString *string = [self.name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *url = [NSString stringWithFormat:@"http://food.boohee.com/fb/v1/foods/extra_search?page=%ld&order_asc=desc&q=%@", (long)self.count, string];
    NSLog(@"%@", url);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"%@", responseObject);
        NSArray *array = responseObject[@"foods"];
        if (array.count > 0) {
            for (NSDictionary *dict in array) {
                FoodSearch *mode = [[FoodSearch alloc] init];
                [mode setValuesForKeysWithDictionary:dict];
                [self.listArrs addObject:mode];
            }
            self.count += 1;
            [self.tableView reloadData];
            [self.tableView.mj_footer endRefreshing];
        } else {
            NSLog(@"11111");
            [self.tableView.mj_footer endRefreshing];
            [self.tableView.mj_footer removeFromSuperview];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
}

- (void)requestFoodData
{
    // 清空数组
    self.listArrs = nil;
    NSString *string = [self.name stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *url = [NSString stringWithFormat:@"http://food.boohee.com/fb/v1/foods/extra_search?page=1&order_asc=desc&q=%@", string];
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager GET:url parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@", responseObject);
        NSArray *array = responseObject[@"foods"];
        for (NSDictionary *dict in array) {
            FoodSearch *mode = [[FoodSearch alloc] init];
            [mode setValuesForKeysWithDictionary:dict];
            [self.listArrs addObject:mode];
        }
        [self.tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@", error);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.listArrs.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    FoodSearchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    FoodSearch *model = self.listArrs[indexPath.row];
    cell.nameLable.text = model.name;
    cell.caloryLable.textColor = [UIColor redColor];
    cell.caloryLable.text = model.calory;
    cell.weightLable.text = [NSString stringWithFormat:@" 大卡/%@克", model.weight];
    if (!model.thumb_image_url) {
        cell.imageView1.image = [UIImage imageNamed:@"imageDownloadFail"];
    } else {
        cell.imageView1.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:model.thumb_image_url]]];
    }
    
    cell.backgroundColor = [UIColor colorWithWhite:0.970 alpha:1.000];
    cell.imageView1.layer.masksToBounds = YES;
    cell.imageView1.layer.cornerRadius = 50 / 2.0f; //设置为图片宽度的一半出来为圆形
    cell.imageView1.layer.borderWidth = 3.0f; //边框宽度
    cell.imageView1.layer.borderColor = [[UIColor whiteColor] CGColor]; //边框颜色
    // Configure the cell...
    
    if ([model.health_light.stringValue isEqualToString:@"1"]) {
        cell.imageView2.backgroundColor = [UIColor greenColor];
    } else if ([model.health_light.stringValue isEqualToString:@"2"]) {
        cell.imageView2.backgroundColor = [UIColor colorWithRed:1.000 green:0.839 blue:0.242 alpha:1.000];
    } else {
        cell.imageView2.backgroundColor = [UIColor redColor];
    }
    cell.imageView2.layer.masksToBounds = YES;
    cell.imageView2.layer.cornerRadius = 10 / 2.0f; //设置为图片宽度的一半出来为圆形
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    FoodSearch *model = self.listArrs[indexPath.row];
    FoodDetailViewController *detail = [[FoodDetailViewController alloc] init];
    detail.code = model.code;
    [self.navigationController pushViewController:detail animated:YES];
}




/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
